import React, { KeyboardEvent, useRef, useState } from "react";
import dayjs from "dayjs";
import { v4 as uuidv4 } from "uuid";

interface IProp {
  onSubmit: (data: ITodo) => void;
}

export default function Input(props: IProp) {
  const [compositon, setComposition] = useState<boolean>(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const keyDownHandler = (e: KeyboardEvent) => {
    if (!compositon) {
      const keyCode = e.code;
      const submitHandler = props.onSubmit;
      if (keyCode === "Enter" || keyCode === "NumpadEnter") {
        if (inputRef.current !== null && inputRef.current.value !== "") {
          const toSubmit: ITodo = {
            id: uuidv4(),
            content: inputRef.current.value,
            finished: false,
            ctime: dayjs().valueOf(),
            mtime: dayjs().valueOf(),
          };
          console.log("Submit:", toSubmit);
          inputRef.current.value = "";
          submitHandler(toSubmit);
        }
      }
    }
  };
  return (
    <input
      className="input-submit"
      onKeyDown={keyDownHandler}
      onCompositionStart={() => {
        setComposition(true);
      }}
      onCompositionEnd={() => {
        setComposition(false);
      }}
      ref={inputRef}
    />
  );
}
